﻿using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.Linq;
using System.Linq;

namespace SBToolkit.LinqToSql
{
    /// <summary>
    /// Converts .NET types.
    /// </summary>
    public static class Converter
    {
        /// <summary>
        /// Converts query results to the <see cref="IDataReader"/>.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="db">The <see cref="DataContext"/> of current connection.</param>
        /// <returns>Resulting <see cref="IDataReader"/> object.</returns>
        public static IDataReader ToDataReader(this IQueryable query, DataContext db)
        {
            DbCommand command = db.GetCommand(query);
            command.Connection.Open();
            IDataReader reader = command.ExecuteReader();
            command.Connection.Close();

            return reader;
        }

        /// <summary>
        /// Converts query results to the <see cref="DataTable"/>.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="db">The <see cref="DataContext"/> of current connection.</param>
        /// <returns>Resulting <see cref="DataTable"/> object.</returns>
        public static DataTable ToDataTable(this IQueryable query, DataContext db)
        {
            IDataReader reader = query.ToDataReader(db);
            var table = new DataTable();
            table.Load(reader);

            return table;
        }

        /// <summary>
        /// Converts source to the <see cref="EntitySet{T}"/>.
        /// </summary>
        /// <typeparam name="T">The type of entity.</typeparam>
        /// <param name="source">The source.</param>
        /// <returns>Resulting <see cref="EntitySet{T}"/> object.</returns>
        public static EntitySet<T> ToEntitySet<T>(this IEnumerable<T> source) where T : class
        {
            var entitySet = new EntitySet<T>();
            entitySet.AddRange(source);
            return entitySet;
        }
    }
}
